package com.zhuzi.guicollect.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.FileReader;

/**
 * @Author: MI
 * @Date: 2021/10/31/23:57
 * @Description:
 */
@Slf4j
public class JSrun {
    public static UserNamePwd exect(String userName, String userPwd) {
        final ClassPathResource classPathResource = new ClassPathResource("crypto-js-3.3.0-min.js");
        final File file;
        UserNamePwd userNamePwd = null;
        try {
            file = classPathResource.getFile();
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            // FileReader的参数为所要执行的js文件的路径
            engine.eval(new FileReader(file));
            if (engine instanceof Invocable) {
                Invocable invocable = (Invocable) engine;
                JSLLogin executeMethod = invocable.getInterface(JSLLogin.class);
                userNamePwd = new UserNamePwd();
                userNamePwd.setEncName(executeMethod.jslencode(userName, "397151C04723421F"));
                userNamePwd.setEncPwd(executeMethod.jslencode(userPwd, "397151C04723421F"));
                log.info("解密用户{}", userNamePwd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userNamePwd;
    }


    public static class UserNamePwd {
        private String userName;
        private String userPwd;
        private String encName;
        private String encPwd;

        @Override
        public String toString() {
            return "UserNamePwd{" +
                    "userName='" + userName + '\'' +
                    ", userPwd='" + userPwd + '\'' +
                    ", encName='" + encName + '\'' +
                    ", encPwd='" + encPwd + '\'' +
                    '}';
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getUserPwd() {
            return userPwd;
        }

        public void setUserPwd(String userPwd) {
            this.userPwd = userPwd;
        }

        public String getEncName() {
            return encName;
        }

        public void setEncName(String encName) {
            this.encName = encName;
        }

        public String getEncPwd() {
            return encPwd;
        }

        public void setEncPwd(String encPwd) {
            this.encPwd = encPwd;
        }
    }
}
